package com.guojian.jdbc.sql;

import com.github.pagehelper.parser.CountSqlParser;
import com.guojian.jdbc.DBType;

//@Component
//@ConditionalOnProperty(value = "pagehelper.helperDialect", havingValue = "oracle")
public class OracleParser implements SqlParser {

	private final CountSqlParser countParser = new CountSqlParser();

	@Override
	public String getCountSql(String sql) {
		return countParser.getSmartCountSql(sql);
	}

	@Override
	public String getPageSql(String sql, Integer offset, Integer limit) {
		Integer endRowNum = offset + limit;
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append("SELECT * FROM ( ");
		sqlBuilder.append(" SELECT TMP_PAGE.*, ROWNUM ROW_NO FROM ( ");
		sqlBuilder.append(sql);
		sqlBuilder.append(" ) TMP_PAGE WHERE ROWNUM <=  " + endRowNum);
		sqlBuilder.append(" ) WHERE ROW_NO >  " + offset);
		return sqlBuilder.toString();
	}

	@Override
	public DBType getDBType() {
		return DBType.oracle;
	}

	public static void main(String[] args) {
		String sql = "select USER_ID from SYS_USER  ORDER BY user_id";
		SqlServerParser spa = new SqlServerParser();
		String newSql = spa.convertToPageSql(sql, 1, 5);
		System.out.println("newSql = " + newSql);

		OracleParser opa = new OracleParser();
		String newSql1 = opa.getPageSql(sql, 1, 5);
		System.out.println("newSql1 = " + newSql1);

		/*SELECT COUNT(*)
		FROM aa
		=======================================
		SELECT *
		FROM (
			SELECT XX.*, ROWNUM AS RN
			FROM (
				SELECT *
				FROM aa
				ORDER BY name
			) XX
			WHERE ROWNUM <= 11
		) XXX
		WHERE RN > 1
		========================================
		SELECT *
		FROM (
			SELECT *, ROW_NUMBER() OVER () AS ROWNUM
			FROM user
			WHERE name = 'guojian'
		) XX
		WHERE ROWNUM > 1
			AND ROWNUM <= 11*/
	}
}
